package leetcode101.complex_datastructure;

/**
 * @author Synhard
 * @version 1.0
 * @class Code8
 * @description TODO
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-07-15 9:52
 */
public class Code8 {
    public static void main(String[] args) {

    }

    public int numSimilarGroups(String[] strs) {
        NumSimilarGroupsDSU dsu = new NumSimilarGroupsDSU(strs.length);
        for (int i = 0; i < strs.length; i++) {
            for (int j = i + 1; j < strs.length; j++) {
                if (checkSimilar(strs[i], strs[j])) {
                    dsu.union(i, j);
                }
            }
        }
        return dsu.getCount();
    }

    private boolean checkSimilar(String s1, String s2) {
        int diff = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                diff++;
            }
            if (diff > 2) {
                return false;
            }
        }
        return true;
    }
}

class NumSimilarGroupsDSU {
    int[] parent;
    int[] size;
    int count;

    NumSimilarGroupsDSU(int n) {
        this.count = n;
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
    }

    int find(int p) {
        while (p != parent[p]) {
            parent[p] = parent[parent[p]]; // 路径压缩
            p = parent[p];
        }
        return p;
    }

    void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);
        if (pRoot == qRoot) {
            return;
        }
        count--;
        if (size[pRoot] > size[qRoot]) { // p所在的树的节点数量更多
            parent[qRoot] = pRoot;
            size[pRoot] += size[qRoot];
            return;
        }
        parent[pRoot] = qRoot;
        size[qRoot] += size[pRoot];
    }

    int getCount() {
        return count;
    }
}
/*
并查集的应用
 */